import os
import sys
import logging
import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.openapi.docs import get_swagger_ui_html, get_redoc_html
from fastapi.staticfiles import StaticFiles

# 添加当前目录到Python路径
current_dir = os.path.dirname(os.path.abspath(__file__))
parent_dir = os.path.dirname(current_dir)
sys.path.insert(0, parent_dir)

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.StreamHandler(),
        logging.FileHandler('backend.log', encoding='utf-8')
    ]
)
logger = logging.getLogger('TWRPA-Backend')

# 创建必要的目录
os.makedirs(os.path.join(current_dir, "data", "processes"), exist_ok=True)
os.makedirs("uploads/data_clean", exist_ok=True)
os.makedirs("results/data_clean", exist_ok=True)
os.makedirs(os.path.join(current_dir, "static"), exist_ok=True)

# 创建favicon文件
favicon_path = os.path.join(current_dir, "static", "favicon.png")
if not os.path.exists(favicon_path):
    # 创建一个简单的favicon图标
    try:
        import base64
        from PIL import Image, ImageDraw
        
        # 创建一个简单的32x32像素的图像
        img = Image.new('RGBA', (32, 32), color=(0, 0, 0, 0))
        draw = ImageDraw.Draw(img)
        
        # 画一个简单的图标
        draw.rectangle([(8, 8), (24, 24)], fill=(52, 152, 219))
        draw.rectangle([(10, 10), (22, 22)], fill=(41, 128, 185))
        
        # 保存图标
        img.save(favicon_path, "PNG")
        logger.info(f"已创建favicon图标: {favicon_path}")
    except ImportError:
        # 如果PIL库不可用，创建一个简单的1x1像素的favicon
        with open(favicon_path, "wb") as f:
            f.write(base64.b64decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="))
        logger.info(f"已创建简单favicon图标: {favicon_path}")
    except Exception as e:
        logger.warning(f"无法创建favicon图标: {str(e)}")

# 导入所需模块
from backend.database import init_db
from backend.routes import auth, process, settings, stats, executions, shop, item, brand
from backend.wingknife.routes import router as wingknife_router
from backend.data_clean.routes import router as data_clean_router
from backend.config.routes import router as config_router
from backend.sku.api import router as sku_router
from backend.scheduler.scheduler import start_scheduler, shutdown_scheduler, scheduler
from backend.scheduler.jobs import add_jobs

# 创建FastAPI应用
app = FastAPI(
    title="AI*RPA",
    description="智能化RPA软件API",
    version="1.0.0",
    docs_url=None,  # 禁用默认的/docs路径
    redoc_url=None  # 禁用默认的/redoc路径
)

# 配置静态文件
app.mount("/static", StaticFiles(directory=os.path.join(current_dir, "static")), name="static")

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 添加路由
app.include_router(auth.router)
app.include_router(process.router)
app.include_router(settings.router)
app.include_router(stats.router)
app.include_router(executions.router)
app.include_router(wingknife_router)
app.include_router(data_clean_router)
app.include_router(config_router)
app.include_router(shop.router, prefix="/api/shop", tags=["shop"])
app.include_router(item.router, prefix="/api/item", tags=["item"])
app.include_router(sku_router, prefix="/api/sku", tags=["SKU管理"])
app.include_router(brand.router, prefix="/api/brand", tags=["品牌管理"])

@app.get("/docs", include_in_schema=False)
async def custom_swagger_ui_html():
    return get_swagger_ui_html(
        openapi_url=app.openapi_url,
        title=f"{app.title} - Swagger UI",
        oauth2_redirect_url=app.swagger_ui_oauth2_redirect_url,
        swagger_js_url="https://cdn.jsdelivr.net/npm/swagger-ui-dist@4/swagger-ui-bundle.js",
        swagger_css_url="https://cdn.jsdelivr.net/npm/swagger-ui-dist@4/swagger-ui.css",
        swagger_favicon_url="/static/favicon.png"
    )

@app.get("/redoc", include_in_schema=False)
async def redoc_html():
    return get_redoc_html(
        openapi_url=app.openapi_url,
        title=f"{app.title} - ReDoc",
        redoc_js_url="https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js",
        redoc_favicon_url="/static/favicon.png"
    )

@app.get("/")
async def root():
    return {"message": "Welcome to AI*RPA API"}

@app.get("/health")
async def health_check():
    return {"status": "healthy"}

if __name__ == "__main__":
    # 初始化数据库表
    init_db()
    
    # 启动定时任务
    start_scheduler()
    add_jobs(scheduler)
    
    logger.info("=" * 50)
    logger.info("正在启动后端服务...")
    host = "0.0.0.0"
    port = 8000
    logger.info(f"服务将运行在: http://{host}:{port}")
    logger.info(f"API文档地址: http://{host}:{port}/docs")
    logger.info(f"ReDoc文档地址: http://{host}:{port}/redoc")
    logger.info(f"本地访问地址: http://127.0.0.1:{port}")
    logger.info("=" * 50)
    
    try:
        uvicorn.run(
            app, 
            host=host, 
            port=port
        )
    finally:
        # 确保在应用关闭时停止调度器
        shutdown_scheduler() 